<?php

namespace app\common\model;

use helper\Files;
use think\model\Collection;

class AttachmentModel extends BaseModel
{

  protected $table = 'attachment';
  //开启自动写入时间戳
  protected $autoWriteTimestamp = false;

  /**
   * 格式化列表
   * @param Collection $list
   * @return mixed
   */
  public function _formatList($list)
  {
    $groupIds = array_unique($list->column('group_id'));
    $groupNames = AttachmentGroupModel::where('id', 'in', $groupIds)->column('group_name', 'id');
    $groupNames[0] = '未分组';
    foreach ($list as $k => $v) {
      $list[$k]['file_size'] = Files::byteFormat($v['file_size']);
      $list[$k]['upload_time'] = date('Y-m-d H:i:s', $v['upload_time']);
      $list[$k]['group_name'] = $groupNames[$v['group_id']] ?? '-';
    }
    return $list;
  }
    /**
     * 获取json格式附件资源
     * @param $urls
     * @param int $type
     * @return array|mixed|string
     * @throws \Exception
     */
    public function getJson($urls,$type=1){
        switch ($type){
            case 1: //单附件
                $list = \app\common\model\AttachmentModel::where('file_url', $urls)->select()->toJson();
                break;
            case 2: //逗号隔开多附件
                $list = \app\common\model\AttachmentModel::where('file_url','in', $urls)->select()->toJson();
                break;
            default:
                $list = $urls;
                break;
        }
        return $list;
    }
}
